import {isEmpty} from "@/utils/validate";

/**
 * 缓存类型
 */
export const storeType = {
  local: 0,
  session: 1,
};

/**
 * 获取缓存
 * @param name
 * @param type
 * @returns {*}
 */
export const getStore = (name, type) => {
  let obj = {};
  //读取storage
  if(type === storeType.local) {
    obj = window.localStorage.getItem(name);
  } else if(type === storeType.session) {
    obj = window.sessionStorage.getItem(name);
  } else {
    obj = window.sessionStorage.getItem(name);
    if(isEmpty(obj)) {
      obj = window.localStorage.getItem(name);
    }
  }
  if(isEmpty(obj)) {
    return null;
  }
  //解析数据
  obj = JSON.parse(obj);
  let value = null;
  if(obj.dataType === "string") {
    value = obj.value;
  } else if(obj.dataType === "number")  {
    value = Number(obj.value);
  } else if(obj.dataType === "boolean") {
    value = eval(obj.value);
  } else if(obj.dataType === "object") {
    value = JSON.parse(obj.value);
  } else {
    value = obj.value;
  }
  return value;
}

/**
 * 存储缓存
 * @param name
 * @param value
 * @param type
 */
export const setStore = (name, value, type = storeType.local) => {
  let obj = {
    dataType: typeof value,
    value: value,
    type: type,
    datatime: new Date().getTime(),
  };
  if(type) {
    window.sessionStorage.setItem(name, JSON.stringify(obj));
  } else {
    window.localStorage.setItem(name, JSON.stringify(obj));
  }
}

/**
 * 删除缓存
 * @param name
 * @param type
 */
export const removeStore = (name, type) => {
  if(type === storeType.local) {
    window.localStorage.removeItem(name);
  } else if(type === storeType.session) {
    window.sessionStorage.removeItem(name);
  } else {
    window.localStorage.removeItem(name);
    window.sessionStorage.removeItem(name);
  }
}

/**
 * 获取全部缓存
 * @param type
 */
export const getAllStore = type => {
  let store = [];
  type = type ? type : storeType.local;
  const storage = type ? window.sessionStorage : window.localStorage;
  for(let i = 0; i <= storage.length; i++) {
    list.push({
      name: storage.key(i),
      value: getStore(name, type),
    });
  }
  return list;
}

/**
 * 清空全部缓存
 * @param type
 */
export const clearStore = type => {
  if(type) {
    window.sessionStorage.clear();
  } else {
    window.localStorage.clear();
  }
}
